/**
 * 完成存件接口
 * 
 * 接口说明：
 * - 用于完成存件操作，将存件状态从"未存件"更新为"已存件"
 * - 需要携带token进行身份验证
 * - 需要传递存件码作为路径参数
 */

import { API_BASE_URL, getHeaders } from '../config'
import type { ApiResponse } from '../types/common'

/**
 * 完成存件响应数据
 */
export interface CompleteStorageResponseData {
  id: number | null
  code: string
  name: string | null
  description: string | null
  status: number
  createTime: string | null
  expireTime: string | null
  statusRecords: any | null
  teacherName: string | null
  qrCode: string | null
  cabinetName: string | null
  location: string | null
}

/**
 * 完成存件接口
 * 
 * @param storageCode 存件码
 * @returns Promise<ApiResponse<CompleteStorageResponseData>>
 * 
 * @example
 * ```typescript
 * // 请求示例
 * const storageCode = "CJ20250930172248-20" // 存件码
 * 
 * try {
 *   const response = await completeStorageByCode(storageCode)
 *   console.log('完成存件成功:', response.data)
 *   console.log('存件ID:', response.data.id)
 *   console.log('存件码:', response.data.code)
 *   console.log('存件状态:', response.data.status)
 *   console.log('柜子名称:', response.data.cabinetName)
 *   console.log('位置:', response.data.location)
 * } catch (error) {
 *   console.error('完成存件失败:', error)
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 成功响应示例
 * {
 *   "code": 200,
 *   "msg": "操作成功",
 *   "data": {
 *     "id": null,
 *     "code": "CJ20251011133429-21",
 *     "name": null,
 *     "description": null,
 *     "status": 2,
 *     "createTime": null,
 *     "expireTime": null,
 *     "statusRecords": null,
 *     "teacherName": null,
 *     "qrCode": null,
 *     "cabinetName": null,
 *     "location": null
 *   }
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 失败响应示例
 * {
 *   "code": 404,
 *   "msg": "存件记录不存在",
 *   "data": null
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 认证失败响应示例
 * {
 *   "code": 401,
 *   "msg": "未授权访问，请先登录",
 *   "data": null
 * }
 * ```
 */
export const completeStorageByCode = async (storageCode: string): Promise<ApiResponse<CompleteStorageResponseData>> => {
  try {
    // 验证参数
    if (!storageCode || storageCode.trim() === '') {
      throw new Error('存件码不能为空')
    }

    const response = await fetch(`${API_BASE_URL}/api/storage/complete-by-code/${storageCode}`, {
      method: 'POST',
      headers: {
        ...getHeaders(),
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      if (response.status === 401) {
        throw new Error('未授权访问，请先登录')
      }
      if (response.status === 404) {
        throw new Error('存件记录不存在')
      }
      if (response.status === 400) {
        throw new Error('存件状态异常，无法完成存件')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: ApiResponse<CompleteStorageResponseData> = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.msg || '完成存件失败')
    }

    return result
  } catch (error) {
    console.error('完成存件接口调用失败:', error)
    throw error
  }
}
